package com.cnap.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.cnap.config.LogSysConfig;
import com.cnap.model.common.CommonResult;
import com.cnap.model.log.OperationLog;
import com.cnap.service.OperationLogService;
import com.cnap.utils.JsonUtil;
import com.cnap.utils.TokenUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 操作日志服务实现类
 *
 * @author xc
 **/
@Service
public class OperationLogServiceImpl implements OperationLogService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OperationLogServiceImpl.class);
    private static final String SAVE_LOG_PATH = "/monitor/statistic/log/save";

    private final LogSysConfig logSysConfig;

    @Autowired
    public OperationLogServiceImpl(LogSysConfig logSysConfig) {
        this.logSysConfig = logSysConfig;
    }

    /**
     * 保存操作日志
     *
     * @param operationLog 操作日志
     * @return 结果
     */
    @Override
    public boolean saveOperationLog(OperationLog operationLog) {
        // 拼接url
        String url = logSysConfig.getUrl() + SAVE_LOG_PATH;
        // 发送请求
        HttpResponse response =
                HttpRequest.post(url).header(HttpHeaders.AUTHORIZATION, TokenUtils.getTOKEN())
                        .body(JsonUtil.objectToJsonStr(operationLog)).execute();
        // 解析响应
        if (!response.isOk()) {
            LOGGER.error("can't save operation log, log={}", operationLog);
            return false;
        }
        // 解析json
        CommonResult<String> result = JsonUtil.jsonStrToObject(response.body(), new TypeReference<CommonResult<String>>() {
        });
        if (Objects.nonNull(result) && 200 != result.getCode()) {
            String res = response.body();
            LOGGER.error("operation log system save operation log error, log={}, response={}", operationLog, res);
            return false;
        }
        return true;
    }

    /**
     * 保存操作日志
     *
     * @param operationType 操作类型
     * @param message       信息
     * @return 结果
     */
    @Override
    public boolean saveOperationLog(String operationType, String message) {
        OperationLog operationLog = new OperationLog();
        // 类型
        operationLog.setOperationType(operationType);
        // 信息
        operationLog.setMessage(message);
        // 用户
        operationLog.setUserName(TokenUtils.getUserName());

        return saveOperationLog(operationLog);
    }
}
